#!/usr/bin/python3.6
import cgi
import cgitb
import sqlite3

from quote import Quote
from sanitize import sanitize_html
from templating import render

cgitb.enable()

print("Content-type: text/html\n")

form = cgi.FieldStorage()
id = form.getfirst("id", "")

connection = sqlite3.connect("quotes.sqlite")
cursor = connection.cursor()

quote = Quote.from_row(
    cursor.execute(
        f"SELECT {','.join(Quote.columns)} FROM quotes WHERE id = ? LIMIT 1",
        [id],
    ).fetchone()
)

names = set()
cursor.execute("SELECT DISTINCT author FROM quotes")
names |= {name for (name,) in cursor.fetchall()}
cursor.execute("SELECT DISTINCT writer FROM quotes")
names |= {name for (name,) in cursor.fetchall()}

connection.close()

with open("templates/edit.html", encoding="utf-8") as file:
    template = file.read()
print(
    render(
        template,
        {
            "people_names_datalist": '<datalist id="people-names">'
            + "".join(f'<option value="{sanitize_html(name)}" />' for name in names)
            + "</datalist>",
            **quote.to_dict(),
        },
    )
    .encode("ascii", "xmlcharrefreplace")
    .decode("ascii")
)
